package com.concurrence;

import com.Example.Model.Transfer.Transfer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainJksClient;
import com.protos.Peer;
import org.apache.commons.codec.binary.Hex;

import java.util.Random;


/**
 * 多节点往同一节点转账
 *
 * @author zyf
 */
public class AnyToSpecified implements Runnable {

    private Peer.ChaincodeId contractAssetsId = Peer.ChaincodeId.newBuilder().setChaincodeName("ContractAssetsTPL").setVersion(1).build();

    // 节点5的值
    private volatile int node5Value;
    // 转出去的
    private volatile int[] amount_out = {0, 0, 0, 0, 0};

    // 各个节点的账户地址
    private String[] node_addr = {"121000005l35120456", "12110107bi45jh675g", "122000002n00123567", "921000005k36123789", "921000006e0012v696"};

    @Override
    public void run() {
        try {
            Random random = new Random();
            for (int i = 1; i <= 200; i++) {

                // 0~3的随机数,正好对应数组下标（前4个节点并发的向节点5转账）
                int rndNodeFrom = random.nextInt(4);
                // 固定的账户4
                int NodeTo = 4;

                // 随机金额5
                int amount = random.nextInt(5) + 1;
                // 固定金额
//                int amount = 3;

                // 构建参数
                Transfer.TransferBuilder builder = Transfer.builder();
                builder.from(node_addr[rndNodeFrom]);
                builder.to(node_addr[NodeTo]);
                builder.amount(amount);

                // 转出值
                amount_out[rndNodeFrom] -= amount;
                // 转入
                node5Value += amount;

                String str_trans = JSON.toJSONString(builder.build());

                System.out.println("jks/" + node_addr[rndNodeFrom] + ".node" + (rndNodeFrom + 1) + ".jks");

                RepChainJksClient adminClient = new RepChainJksClient(
                        "localhost:8081",
                        "jks/" + node_addr[rndNodeFrom] + ".node" + (rndNodeFrom + 1) + ".jks", "123",
                        node_addr[rndNodeFrom] + ".node" + (rndNodeFrom + 1));

                // 管理员证书ID
                Peer.CertId adminCertId = Peer.CertId.newBuilder().setCreditCode(node_addr[rndNodeFrom]).setCertName("node" + (rndNodeFrom + 1)).build();

                //这个是给转账交易示范用的，此ID需要与repchain合约部署的一致
                Peer.Transaction transfer = adminClient.createTransactionForInvoke(adminCertId, contractAssetsId, "transfer", str_trans);

                // 将交易数据post过去
                JSONObject transferResult = adminClient.postTranByString(JSONObject.toJSONString(Hex.encodeHexString(transfer.toByteArray())));
                System.out.println(Thread.currentThread().getName() + ": " + transferResult);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public int[] getAmount_out() {
        return amount_out;
    }

    public int getNode5Value() {
        return node5Value;
    }
}
